const {
    MAILER_CONFIG,
    Option
} = require('../config');

const {
    execSQL
} = require('../db/mysql')

const nodemailer = require('nodemailer')

const {generatePassword} = require('../utils')

//是否已发送过验证码
const hasCode = ({email}) =>{
    let sql = `select code from code where email= '${email}'`
    return execSQL(sql).then(res => {
        return res[0] ? true:false;
    }).catch(e => {
        return false;
    })
}

//删除冗余验证码
const deleteCode = ({email})=>{
    let sql = `delete from code where email = '${email}' or expire <= '${new Date(Date.now()).toISOString().replace('T', ' ').slice(0, -5)}'`
    return execSQL(sql).then(res => {
        return true;
    }).catch(e => {
        throw e;
        return false;
    })
}

//发送邮箱验证码
const sendEmail = async ({
    username,
    type,
    email,
}) => {

    
    let checkCode = Math.random().toString().substr(2, 6);

    console.log(checkCode, 'checkCode');
    //建立一个smtp连接
    let transporter = nodemailer.createTransport(MAILER_CONFIG)
    let tag = false;

    
    
    //发送验证码
    await new Promise((resolve,reject)=>{
        transporter.sendMail(Option({
            username,
            type,
            email,
            checkCode
        }), async function (err, msg) {
            if (err) {

                transporter.close()
                resolve(false)
            } else {

                transporter.close();
                resolve(true)
            }
        })
        return false;
    }).then(res=>{
        tag = res
    })
    //如果发送成功
    if(tag){
        await hasCode({email}).then(async (r)=>{
            if(r) deleteCode({email}).then();
            
        })

        let sql = `insert into code (email,code,expire) values('${email}','${checkCode}','${new Date(Date.now() + 900000).toISOString().replace('T', ' ').slice(0, -5)}')`
        
        return execSQL(sql).then(res => {
            if (res.affectedRows > 0)
                return {code:checkCode};
            return false
        }).catch(e => {
            return false;
        })
        
    }else{
        return Promise.resolve(false).then(r=>r)
    }

}

//校验验证码
const validCode = ({code,email})=>{
    console.log(code,email)

    let sql = `select id from code where email = '${email}' and code = '${code}' and expire >= '${new Date(Date.now()).toISOString().replace('T', ' ').slice(0, -5)}'`
    return execSQL(sql).then(res => {
        return res[0];
    }).catch(e => {
        throw e;
        return false;
    })
}


//检查邮箱是否已被注册
const hasEmail = (
    {email}
) => {
    let sql = `select email from users where email= '${email}'`
    return execSQL(sql).then(res => {
        return res[0] ? true:false;
    }).catch(e => {
        return false;
    })
}



//检查用户名是否已被注册
const hasUser = ({
    username
}) => {
    let sql = `select username from users where username= '${username}'`
    return execSQL(sql).then(res => {
        return res[0] ? true:false;
    }).catch(e => {
        return false;
    })
}



//注册
const register = async ({
    username,
    password,
    email,
    nickname,

}) => {

            let sql = `insert into users (nickname,username,password,email,created) values('${nickname}','${username}','${generatePassword(password)}','${email}','${new Date(Date.now()).toISOString().replace('T',' ').slice(0,-5)}') `;

            return execSQL(sql).then(res => {
                return res.affectedRows > 0 ;
            }).catch(e => {
                throw e;
                return false;
            })
   
    
}






module.exports = {
    register,
    sendEmail,
    hasEmail,
    hasUser,
    validCode,
}